import uuid
from datetime import datetime

from flask import Blueprint, render_template, request, jsonify, session
from flask_login import login_required
from sqlalchemy import and_
from werkzeug.security import generate_password_hash

from applications.common import curd
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id, enable_is_on_sale, \
    disable_is_on_sale
from applications.common.helper import ModelFilter
from applications.common.utils.getopenid import get_openid, token
from applications.common.utils.http import table_api, success_api, fail_api, wxuser_success_api, goods_api, carts_api, \
    coupon_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.exts import db
from applications.exts.cache import cache
from applications.models import Role, Power, User, Goods, Classify, Carts, Coupon, Coupon_Class
from applications.models.wx_user import WxUser
from applications.schemas import RoleOutSchema, PowerOutSchema2, WxUserOutSchema, GoodsOutSchema, WxUClassifyOutSchema, \
    CartsOutSchema, CouponOutSchema
from applications.common.utils import upload as upload_curd

coupon = Blueprint('coupon', __name__, url_prefix='/coupon')


@coupon.route('/')
@login_required
def main():
    return render_template('coupon/main.html')


#   优惠卷查询
@coupon.route('/data')
@login_required
# @authorize("admin:user:main", log=True)
def data():
    # 获取请求参数
    couponname = xss_escape(request.args.get('couponname', type=str))
    coupontype = xss_escape(request.args.get('coupontype', type=str))
    # 查询参数构造
    mf = ModelFilter()
    if couponname:
        mf.contains(field_name="coupon_name", value=couponname)
    if coupontype:
        # coupon = Coupon_Class.query.filter(Coupon_Class.name == coupontype).first()
        # class_id=coupon.id
        # print('class_id:',class_id)
        mf.contains(field_name="coupon_type", value=coupontype)
    # if dept_id:
    #     mf.exact(field_name="dept_id", value=dept_id)
    # orm查询

    # 使用分页获取data需要.items
    coupon = Coupon.query.filter(and_(mf.get_filter(model=Coupon), Coupon.is_del == 0)).layui_paginate()
    count = coupon.total
    # 返回api
    return table_api(data=model_to_dicts(schema=CouponOutSchema, data=coupon.items), count=count)


# 增加优惠卷
@coupon.route('/add')
@login_required
# @authorize("admin:user:add", log=True)
def add():
    coupons = Coupon_Class.query.filter().all()
    return render_template('coupon/add.html', coupons=coupons)


# add优惠卷
@coupon.route('/addcoupon', methods=["POST"])
# @authorize("admin:user:add", log=True)
def adduser():
    req_json = request.json

    # req_json: {'name': '1', 'start': '2022-03-08', 'end': '2022-04-19', 'gtypes': '1', 'minmoney': '1', 'submoney': '1',
    #            'phone': '1', 'file': ''}

    print('req_json:', req_json)

    name = xss_escape(req_json.get('name'))
    start = xss_escape(req_json.get('start'))
    end = xss_escape(req_json.get('end'))
    classify = xss_escape(req_json.get('classify'))

    cl_type = Coupon_Class.query.get(classify)
    print(cl_type.name)
    type = cl_type.name

    minmoney = xss_escape(req_json.get('minmoney'))
    submoney = xss_escape(req_json.get('submoney'))
    number = xss_escape(req_json.get('number'))

    coupon = Coupon()
    coupon.coupon_sn = uuid.uuid4()
    coupon.coupon_name = name
    coupon.coupon_type = type
    coupon.minmoney = minmoney
    coupon.submoney = submoney
    coupon.start_time = start
    coupon.end_time = end
    coupon.numbers = number
    coupon.coupon_status = 1
    coupon.wx_coupon_classifyid = int(classify)

    db.session.add(coupon)
    db.session.commit()
    return success_api(msg="添加成功")


# ⌘+ / ⌘- 展开 / 折叠代码块
# ⌘⇧+ 展开所以代码块
# ⌘⇧- 折叠所有代码块

@coupon.route('/enable', methods=["PUT"])
@login_required
# @authorize("admin:user:edit", log=True)
def enable():
    _id = request.json.get('id')
    if _id:
        res = enable_status(model=Coupon, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启用成功")
    return fail_api(msg="数据错误")


@coupon.route('/disable', methods=["PUT"])
@login_required
# @authorize("admin:user:edit", log=True)
def dis_enable():
    _id = request.json.get('id')
    if _id:
        res = disable_status(model=Coupon, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="销毁成功")
    return fail_api(msg="数据错误")


# 删除
@coupon.route('/remove/<int:id>', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def delete(id):
    # user = User.query.filter_by(id=id).first()
    # user.role = []

    # res = User.query.filter_by(id=id).delete()

    res = Coupon.query.filter_by(id=id).first()
    res.is_del = 1
    db.session.commit()
    # print('res:', res)
    # if not res:
    # return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 批量删除
@coupon.route('/batchRemove', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        # wxuser = WxUser.query.filter_by(id=id).first()
        # user.role = []

        res = Coupon.query.filter_by(id=id).first()
        # print(res)
        res.is_del = 1
        db.session.commit()
    return success_api(msg="批量删除成功")


# ==========分类=======
# 添加分类
@coupon.route('/addcouponclass')
@login_required
def addcouponclass():
    classify = Coupon_Class.query.all()
    return render_template('coupon/classify_add.html', classify=classify)


@coupon.route('/addclassify', methods=["POST"])
@login_required
def addclassify():
    req_json = request.json
    classifyname = xss_escape(req_json.get('classifyname'))

    coupons = Coupon_Class.query.filter(Coupon_Class.name == classifyname).first()
    if coupons:
        return fail_api(msg='分类已存在')
    else:
        cl = Coupon_Class()
        cl.name = classifyname
        db.session.add(cl)
        db.session.commit()
        return success_api(msg='分类添加成功')


# ============wx===============

# 获取优惠卷

@coupon.route('/couponslist', methods=["POST", "GET"])
def couponslist():
    coupons = Coupon.query.filter(and_(Coupon.numbers >= 1, Coupon.coupon_status == 1, Coupon.is_del == 0)).all()
    return coupon_api(usercoupon=model_to_dicts(CouponOutSchema, data=coupons), msg='查询成功')


@coupon.route('/subcoupon', methods=["POST", "GET"])
def subcoupon():
    req_json = request.json
    id = req_json.get('id')
    coupon = Coupon.query.get(id)
    if coupon:
        if coupon.numbers > 1:
            coupon.numbers -= 1
            db.session.commit()
        elif coupon.numbers == 1:
            coupon.is_del = 1
            db.session.commit()
            return wxuser_success_api(msg='操作成功')
        else:
            return wxuser_success_api(msg='操作失败', errno=0)

    return wxuser_success_api(msg='操作成功')
